//
//  AccountingDetailCombine.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 22.03.25.
//

import Foundation
import GRDB

struct AccountingDetailCombine : Identifiable, Hashable {
    
    var id:Int64
    var detail:AccountingDetail
    var category:AccountingCategory
    var book:AccountingBook
    
    static func == (lhs: AccountingDetailCombine, rhs: AccountingDetailCombine) -> Bool {
        return lhs.detail.recordId == rhs.detail.recordId
        && lhs.category.cid == rhs.category.cid
        && lhs.book.bookId == rhs.book.bookId
        && lhs.detail.date == rhs.detail.date
        && lhs.detail.amount == rhs.detail.amount
        && lhs.detail.remark == rhs.detail.remark
    }
    
    static func previewData(name: String = "餐饮", remark: String = "喜家德", icon: String = "linearicon://koi_rice") -> AccountingDetailCombine {
        return AccountingDetailCombine(
            id: 1,
            detail: AccountingDetail(remark: remark),
            category: AccountingCategory(name: name, icon: icon),
            book: AccountingBook(bookName: "默认账本")
        )
    }
    
    /**
     有 remark 使用 remark 没有使用 categoryName
     */
    func getTitle() -> String {
        if let remark = detail.remark {
            if (remark.isEmpty) {
                return category.name.orEmpty
            } else {
                return remark
            }
        } else {
            return category.name.orEmpty
        }
    }
    
    func getSubTitle() -> String {
        if let remark = detail.remark {
            if (remark.isEmpty) {
                return ""
            } else {
                return category.name.orEmpty
            }
        } else {
            return ""
        }
    }
    
    func getAmount() -> String {
        let amount = detail.amount
        if (amount == nil || amount == 0.0) {
            return "¥0"
        }
        var type = "-"
        if (category.getCategoryType() == CategoryType.income) {
            type = "+"
        }
        return "\(type)¥\(String(describing: amount!.toStringWithoutTrailingZeros()))"
    }
    
    func getAmountNoSign() -> String {
        let amount = detail.amount
        if (amount == nil || amount == 0.0) {
            return "¥0"
        }
        return "¥\(String(describing: amount!.toStringWithoutTrailingZeros()))"
    }
    
    func getRemark() -> String {
        return detail.remark ?? ""
    }
    
    func getDateText() -> String {
        let detailDate = detail.date.orEmpty
        print("detailDate \(detailDate)")
        let date = detailDate.toDate() ?? Date()
        print("toDateFromISODateString \(date)")
        return date.toFriendlyString()
    }
    
    func getBookName() -> String {
        return book.bookName.orEmpty
    }
    
    func getCategoryName() -> String {
        return category.name.orEmpty
    }
}
